import axios from 'axios'
import { Session } from '@u/storage'
import { isNull, msg, warning, error, confirm } from '@u/common'
import qs from 'qs'
import { store } from '@/store/index'

// 配置新建一个 axios 实例
const server = axios.create({
    // baseURL: import.meta.env.VITE_API_URL as any,
    timeout: 60000,
})

// 添加请求拦截器
server.interceptors.request.use(
    (config: any) => {
        config.headers.isLoading !== false && store.commit('loadingCount/loading')

        config.url = window.$baseApi + config.url

        if (Session.get('token')) {
            config.headers.common.token = `${Session.get('token')}`
        }

        if (isNull(config.headers.contentType) || config.headers.contentType === 'form') {
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
        } else if (config.headers.contentType === 'json') {
            config.headers['Content-Type'] = 'application/json'
        }

        // get请求映射params参数
        if (config.method === 'get' && (config.headers.contentType === 'form' || isNull(config.headers.contentType))) {
            let url = `${config.url}?`
            for (const propName of Object.keys(config.data || {})) {
                const value = config.data[propName]
                const part = `${encodeURIComponent(propName)}=`
                if (value !== null && typeof (value) !== 'undefined') {
                    if (typeof value === 'object') {
                        for (const key of Object.keys(value)) {
                            const data = `${propName}[${key}]`
                            const subPart = `${encodeURIComponent(data)}=`
                            url += `${subPart + encodeURIComponent(value[key])}&`
                        }
                    } else {
                        url += `${part + encodeURIComponent(value)}&`
                    }
                }
            }
            url = url.slice(0, -1)
            config.data = {}
            config.url = url
        } else if (config.method === 'post' && (config.headers.contentType === 'form' || isNull(config.headers.contentType))) {
            config.data = qs.stringify(config.data)
        }

        return config
    },
    (error: any) => {
        error.config.headers.isLoading !== false && store.commit('loadingCount/loaded')
        return Promise.reject(error)
    },
)

// 添加响应拦截器
server.interceptors.response.use(
    (r:any) => {
        r.config.headers.isLoading !== false && store.commit('loadingCount/loaded')

        const code = r.data.code || 200
        const message = r.data.msg

        r.data.flag = code === 200 ? 1 : 0

        if (code === 401 || code === 1002 || code === 1003 || code === 1005 || code === 1006) {
            warning(`<b>${message}</b>`, '系统提示').then(() => {
                Session.clear()
                window.location.href = '/index'
            }).catch(() => {})
        } else if (code === 500) {
            return Promise.reject(r.data)
        } else if (code !== 200 && code !== 201) {
            return Promise.reject(r.data)
        } else {
            return Promise.resolve(r.data)
        }
    },
    (e) => {
        e.config.headers.isLoading !== false && store.commit('loadingCount/loaded')

        let { message } = e
        if (message === 'Network Error') {
            // message = '网络异常，请稍后重试' //网络异常时，只弹一次错误信息，只能在common.ts中判断
            // error(message)
        } else if (message.includes('timeout')) {
            message = '系统接口请求超时'
            // error(message, 'error', 5 * 1000)
        } else if (message.includes('Request failed with status code')) {
            message = `系统接口${message.substr(message.length - 3)}异常`
            // msg(message, 'error', 5 * 1000)
        }
        const err = {
            code: null,
            msg: message,
        }
        return Promise.reject(err)
    },
)

export default server
